package cn.changein.framework.config.filter;

import cn.changein.framework.util.TraceLogUtils;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**

 */
@Slf4j
public class CommonFilter implements Filter {

    private final String host;

    public CommonFilter(String host) {
        this.host = host;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/group1/") && StringUtils.isNotBlank(host)) {
            //fastdfs请求,本机调试重定向到线上域名
            response.sendRedirect(host + requestURI);
            return;
        }
        if (requestURI.substring(requestURI.lastIndexOf("/") + 1).contains(".")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        try {
            TraceLogUtils.getTraceId();
            log.info("收到请求 URL: {}", requestURI);
            String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);
            if (contentType != null && contentType.contains("boundary")) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
            Map<String, Object> headerMap = new HashMap<String, Object>();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                headerMap.put(headerName, headerValue);
            }
            if (!CollectionUtils.isEmpty(headerMap)) {
                log.info("收到请求头 headerMap={}", JSONObject.toJSONString(headerMap));
            }
            if (contentType != null && contentType.toLowerCase().contains(MediaType.APPLICATION_JSON_VALUE)) {
                try {
                    BodyReaderRequestWrapper bodyReaderRequestWrapper = new BodyReaderRequestWrapper(request);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(bodyReaderRequestWrapper.getInputStream()));
                    String body = IoUtil.read(reader);
                    if (StringUtils.isNotBlank(body)) {
                        log.info("收到请求体参数：{}", JSONObject.parseObject(body).toJSONString());
                    }

                    filterChain.doFilter(bodyReaderRequestWrapper, servletResponse);
                } catch (Exception e) {
                    log.error("parseObject error:{}", e.getMessage());
                }
            } else {
                Map<String, String[]> parameterMap = request.getParameterMap();
                log.info("收到请求参数: {}", JSONObject.toJSONString(parameterMap));
                filterChain.doFilter(servletRequest, servletResponse);
            }

        } finally {
            TraceLogUtils.remove();
        }


    }
}
